package short_semester.questionnaire_planet.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import short_semester.questionnaire_planet.dao.*;
import short_semester.questionnaire_planet.entity.User;
import short_semester.questionnaire_planet.pojo.*;
import short_semester.questionnaire_planet.request.fillRequest.CheckBody;
import short_semester.questionnaire_planet.request.fillRequest.Checks;
import short_semester.questionnaire_planet.response.CommonResponse;
import short_semester.questionnaire_planet.service.analyse.QuestionnaireRecordService;
import short_semester.questionnaire_planet.service.editService.RelationService;
import short_semester.questionnaire_planet.service.fill.SignService;

import java.util.*;

@RestController
@RequestMapping("api/fill")
public class FillController {
    
    @Autowired
    QuestionnaireDao questionnaireDao;
    
    @Autowired
    UserDao userDao;
    
    @Autowired
    QuestionnaireRecordDao questionnaireRecordDao;
    
    @Autowired
    RelationService relationService;
    
    @Autowired
    QuestionnaireRecordService questionnaireRecordService;
    @Autowired
    SingleChoiceQuestionDao singleChoiceQuestionDao;
    @Autowired
    MultiChoiceQuestionDao multiChoiceQuestionDao;
    @Autowired
    SingleChoiceOptionDao singleChoiceOptionDao;
    @Autowired
    MultiChoiceOptionDao multiChoiceOptionDao;
    @Autowired
    SignService signService;
    
    @PostMapping("getqaInfo")
    public CommonResponse getqaInfo(@RequestParam String uuid){
        CommonResponse response = new CommonResponse();
        try {
            Questionnaire questionnaire = questionnaireDao.findByImg(uuid);
            if(questionnaire==null){
                response.setCode(-1);
                response.setMsg("问卷不存在或已关闭");
                return response;
            }else {
                response.setData(questionnaire);
            }
        }catch (Exception e){
            e.printStackTrace();;
            response.error(e.getMessage());
        }
        
        return response;
    }
    
    @PostMapping("isSubmitted")
    public CommonResponse isSubmitted(@RequestParam(required = false) String id,
                                      @RequestParam Integer questionnaireId,
                                      @RequestParam String uuid){
        
        CommonResponse response = new CommonResponse();
        Map<String, Object> map = new HashMap<>();
        Boolean isSubmitted = false;
        Questionnaire questionnaire = questionnaireDao.getById(questionnaireId);
        try {
            try {
                Integer.parseInt(id);
            }catch (Exception e){
                id = null;
            }
            
            if(id!=null && !id.equals("")){
                //用户已登录
                User user = userDao.getById(Integer.parseInt(id));
                
                Optional<QuestionnaireRecord> optional = questionnaireRecordDao.findByUserAndQuestionnaire(user, questionnaire);
                
                if(optional.isPresent()){
                    //有记录
                    QuestionnaireRecord record = optional.get();
                    isSubmitted = record.getIsSubmitted();
                }else{
                    //无记录
                    QuestionnaireRecord record = new QuestionnaireRecord();
                    record.setUser(user);
                    record.setQuestionnaire(questionnaire);
                    record = questionnaireRecordDao.save(record);
                    //将题目记录加载进去
                    questionnaireRecordService.initQuestionRecord(record);
                    
                }

            }else if(uuid!=null&&!uuid.isEmpty()){
                //有临时uuid
                Optional<QuestionnaireRecord> optional = questionnaireRecordDao.findByUuidAndQuestionnaire(uuid,questionnaire);
                if(optional.isPresent()){
                    //有记录
                    QuestionnaireRecord record = optional.get();
                    isSubmitted = record.getIsSubmitted();
                }else {
                    //无记录
                    QuestionnaireRecord record = new QuestionnaireRecord();
                    record.setQuestionnaire(questionnaire);
                    record.setUuid(uuid);
                    record = questionnaireRecordDao.save(record);
                    //将题目记录加载进去
                    questionnaireRecordService.initQuestionRecord(record);
                }
            }else {
                //既无id也无uuid
                //创建新的记录表和uuid
                uuid = UUID.randomUUID().toString();
                QuestionnaireRecord record = new QuestionnaireRecord();
                record.setQuestionnaire(questionnaire);
                record.setUuid(uuid);
                record = questionnaireRecordDao.save(record);
                //将题目记录加载进去
                questionnaireRecordService.initQuestionRecord(record);
            }
            map.put("isSubmitted",isSubmitted);
            map.put("uuid",uuid);
            response.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        
        return response;
    }
    
    @PostMapping("getq")
    public CommonResponse getQ(@RequestParam(required = false) String id,
                               @RequestParam Integer questionnaireId,
                               @RequestParam String uuid){
        CommonResponse response = new CommonResponse();
        Questionnaire questionnaire = questionnaireDao.getById(questionnaireId);
        try {
            if(id!=null && !id.equals("")&&!id.equals("NaN")){
                //用户已登录
                Optional<User> optional = userDao.findById(Integer.parseInt(id));
                if(optional.isPresent()){
                    User user = optional.get();
                    Optional<QuestionnaireRecord> recordOptional = questionnaireRecordDao.findByUserAndQuestionnaire(user, questionnaire);

                    if(recordOptional.isPresent()){
                        Map<String, Object> map = new HashMap<>();
                        map.put("questions",questionnaireRecordService.getQuestionRecordByRecord(recordOptional.get()));
                        map.put("relations",relationService.getRelations(questionnaire));
                        response.setData(map);
                    }else {
                        response.error("该用户未填写过该问卷");
                    }
                    
                }else{
                    response.error("用户不存在");
                    
                }
            }else if(uuid!=null&&!uuid.isEmpty()){
                //有临时记录
                Optional<QuestionnaireRecord> optional = questionnaireRecordDao.findByUuidAndQuestionnaire(uuid, questionnaire);
                if(optional.isPresent()){
                    Map<String, Object> map = new HashMap<>();
                    map.put("questions",questionnaireRecordService.getQuestionRecordByRecord(optional.get()));
                    response.setData(map);
                    
                }else {
                    response.error("该用户未填写过该问卷");
                }
                
            }else{
                response.error("id和uuid怎么都是空的？");
            }
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        
        return response;
        
    }
    
    
    
    @PostMapping("check")
    public CommonResponse check(@RequestBody CheckBody body){
        System.out.println(body);

        Integer questionnaireId = body.getQuestionnaireId();
        List<Checks> checks = body.getChecks();
        CommonResponse response = new CommonResponse();
        try {
            Questionnaire questionnaire = questionnaireDao.getById(questionnaireId);
            if(questionnaire.getStore()!=null&&questionnaire.getStore()<=0){
                response.setCode(-1);
                response.setMsg("问卷余额不足");
                return response;
            }
            List<SingleChoiceOption> singleChoiceOptions = new LinkedList<>();
            List<MultiChoiceOption> multiChoiceOptions = new LinkedList<>();
            for (Checks check : checks) {
                switch (check.getType()){
                    case "radio":
                        SingleChoiceQuestion singleChoiceQuestion = singleChoiceQuestionDao.getById(check.getQuestionId());
                        singleChoiceOptions.addAll(singleChoiceOptionDao.findBySingleChoiceQuestionAndIdIn(singleChoiceQuestion,check.getOptionIds()));
                        break;
                    case "checkbox":
                        MultiChoiceQuestion multiChoiceQuestion = multiChoiceQuestionDao.getById(check.getQuestionId());
                        multiChoiceOptions.addAll(multiChoiceOptionDao.findByMultiChoiceQuestionAndIdIn(multiChoiceQuestion,check.getOptionIds()));
                        break;
                }
            }
            //非并发判断
            if (signService.checkStore(questionnaire,singleChoiceOptions,multiChoiceOptions)) {
                //并发判断
                if (!signService.getStore(questionnaire,singleChoiceOptions,multiChoiceOptions)) {
                    response.setCode(-1);
                    response.setMsg("选项余额不足");
                }
            }else{
                response.setCode(-1);
                response.setMsg("选项余额不足");
            }
            
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        
        return response;
    }
}
